package spring.aop.proxy;

import spring.aop.ProceedingJoinPoint;
import spring.aop.AopProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author cg
 * @date 2023/6/14 18:30
 */
public class JdkDynamicProxy {
    public Object target;//被代理类

    public AopProcessor aopProcessor;//代理类

    public JdkDynamicProxy(Object target, AopProcessor aopProcessor) {
        this.target = target;
        this.aopProcessor = aopProcessor;
    }

    public Object getProxyBean(){
        Object proxyInstance = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //获取真正的代理对象
                Object aop = aopProcessor.getClazz().getConstructor().newInstance();
                //将切面信息包装成ProceedingJoinPoint对象
                ProceedingJoinPoint joinPoint = new ProceedingJoinPoint();
                joinPoint.load(target, method, args);
                //执行beforeMethod
                Method beforeMethod = aopProcessor.getBeforeMethod();
                if (beforeMethod != null) {
                    beforeMethod.invoke(aop,joinPoint);
                }
                //执行被代理类的方法
                Object invoke = method.invoke(target, args);
                //执行afterMethod
                Method afterMethod = aopProcessor.getAfterMethod();
                if (afterMethod != null) {
                    afterMethod.invoke(aop,joinPoint);
                }
                return invoke;
            }
        });
        return proxyInstance;
    }
}
